package com.cec.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil {

    public static String getElement(String url){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/5.0");
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 获取返回的数据，使用Entity封装
            HttpEntity entity = response.getEntity();
            // 使用EntityUtils中的toString方法来解析Entity封装的数据
            String body = EntityUtils.toString(entity);
            // 关闭资源
            response.close();
            httpClient.close();

            return  body;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
